package datasink;

/**
 * Vorlesung: Verteilte Systeme
 * Aufgabe  : 04
 * 
 * @author Benjamin Burchard
 * @author Tell Mueller-Pettenpohl
 * 
 */

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class LogBuilder {

    private FileWriter file;
    private BufferedWriter log;

    /**
     * Sets up the log file, which is saved to the actual directory. Start to
     * log with log(byte[], byte, long)
     * 
     */
    public LogBuilder() {
        try {
            String path = new File(".").getCanonicalPath();
            file = new FileWriter(path + "./VS_lab4_team01_"
                    + System.currentTimeMillis() + ".log");
            log = new BufferedWriter(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Logs a DatagramPacket and writes the log to /packet.log
     * 
     * @param packet
     *            to log
     * @throws SecurityException
     * @throws IOException
     */
    public void log(byte[] data, byte slot, long time) {
        long timestamp = System.currentTimeMillis();
        try {
            this.log.write("Received: " + new String(data) + "(" + time
                    + " next slot: " + slot + ") at " + timestamp + " [Frame: "
                    + (((time) % 100000) / 1000) + "] [Slot: " + (((time)%1000)/50) + "]");
            this.log.newLine();
            this.log.flush();
            System.out.println("Received: " + new String(data) + "(" + time
                    + " next slot: " + slot + ") at " + timestamp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
